
/*---------------------------------------------------------------------------

  FILENAME:
        sock2buf.c

  PURPOSE:
	transport multi sockets command to serial port, 
	accept commands from net sockets, 1 thread 1 socket,
	put cmd to queue, fifo

  REVISION HISTORY:
        Date            Engineer        Revision        Remarks
	16/02/2009	Vincent. Young	1.2	

  NOTES:


  LICENSE:
        Copyright (c) 2009, Vincent Young (vincentgodyoung@hotmail.com)

        This source code is released for free distribution under the terms
        of the GNU General Public License.

----------------------------------------------------------------------------*/

// local project include files
#include "cmdbufqueue.h"
#include "socket.h"

// system library include files
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>

#define LOGREGMODE FALSE

//从socket取数据放入队列
void * sock2buf(void * clientpointer)
{
	char buf[CMDLENGTH];
	int ret;
	int len;
	// 为了多连接不互相串线，需要动态分配clientpointer存储器块避免线程竞争
	// 参见server.c的listening()函数
	int clientfd = *(int *)clientpointer;
	free(clientpointer);

	while(1)
	{
		memset(buf, '\0', CMDLENGTH);
		// 从socket接收数据
		len = TCPBlockRead( clientfd, buf, CMDLENGTH);
		// 把数据存入cmdqueue里
		if (len <= 0)
		{
			printf("sock2buf: sock [%d] recv fail [%d]", clientfd, len);
			break;
		}
		else // if (len > 0)
		{
			// 把命令添加到命令队列
			ret = cmdaddlast(buf, len, clientfd);
			if (ret < 0)
			{
				printf("sock2buf: cmd add failed [%d]\n", ret);
				return NULL;
			}
#if LOGREGMODE
			printf("sock2buf: receive from sock [%d] cmd [%s]\n", clientfd, (char *)(lastcmd->cmd));
#endif
		}
	}
	close(clientfd);
	return NULL;
}
